package com.linkoog.devtools.code_generator.setting.configurable;

import com.linkoog.devtools.code_generator.setting.configurable.ui.TypeMappingPanel;
import com.linkoog.devtools.code_generator.setting.persistent.CodeGenDevToolsPersistent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * Created on 24/08/2019
 *
 * @author JDI
 * @version 2.0.0
 * @since 2.0.0
 */
public class TypeMappingConfigurable implements Configurable {

    private final CodeGenDevToolsPersistent apiCodeDevToolsPersistent;

    private TypeMappingPanel typeMappingPanel;

    public TypeMappingConfigurable() {
        this.apiCodeDevToolsPersistent = ServiceManager.getService(CodeGenDevToolsPersistent.class);
    }

    @Nls(capitalization = Nls.Capitalization.Title)
    @Override
    public String getDisplayName() {
        return "Type Mapping";
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        if (null == typeMappingPanel) {
            typeMappingPanel = new TypeMappingPanel();
        }
        return typeMappingPanel.getMyMainPanel();
    }

    @Override
    public boolean isModified() {
        return ! apiCodeDevToolsPersistent.getTypeMappings().equals(typeMappingPanel.getTypeMappingEditor().getModel().getItems());
    }

    @Override
    public void apply() throws ConfigurationException {
        apiCodeDevToolsPersistent.setTypeMappings(typeMappingPanel.getTypeMappingEditor().apply());
    }

    @Override
    public void reset() {
        typeMappingPanel.getTypeMappingEditor().reset(apiCodeDevToolsPersistent.getTypeMappings());
    }
}
